// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import HorseCtrl from "./HorseCtrl";

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    @property
    moveSpeed: number = 10;

    @property
    farDistance: number = 1500;

    @property(cc.Node)
    horseRoot: cc.Node = null;

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start () {
        cc.game.once('RaceStart', () => {
            this.raceStart();
        });
        this.moveSpeed = 0;
        
    }

    raceStart(){
        let horseSpeed = [];
        this.schedule(() => {
            this.horseRoot.children.forEach((child) => {
                
                horseSpeed.push(child.getComponent(HorseCtrl).moveSpeed);
            })
            console.log(this.findMax(horseSpeed),"最快的速度");
            this.moveSpeed = this.findMax(horseSpeed) - 100;
        }, 0.2,100,0);
    }

    update (dt) {
        if(this.node.x > this.farDistance){
            this.moveSpeed = 0;
        }
        this.node.x += this.moveSpeed * dt;
    }

    findMax(arr: number[]): number | undefined {
        if (arr.length === 0) {
          return undefined; // 当数组为空时返回 undefined
        }
      
        let max = arr[0]; // 初始化最大值为数组的第一个元素
      
        for (let i = 1; i < arr.length; i++) {
          if (arr[i] > max) {
            max = arr[i]; // 找到更大的值，更新 max
          }
        }
      
        return max; // 返回找到的最大值
      }
}
